package com.dd.filter;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.TimerTask;
import javax.servlet.ServletContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.StaleObjectStateException;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate.HibernateOptimisticLockingFailureException;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.dd.entity.*;
import com.dd.dao.*;
import com.dd.service.*;
import com.dd.util.SmsSend;

public class SmsSendTask extends TimerTask {
	private ApplicationContext ctx;
	private static final Log logger = LogFactory.getLog(SystemTimerTask.class);
	private static boolean isRunning = false;
	ServletContext application;

	public SmsSendTask(ServletContext sc) {
		application = sc;
		this.ctx = WebApplicationContextUtils
				.getRequiredWebApplicationContext(sc);
		System.out.println(" SmsSendTask start........................");
	}

	public void run() {
		try {
			if (!isRunning) {
				isRunning = true;
				// 
				int hour = new Date().getHours();
				if (hour < 9 || hour > 21) {

				} else {
					DdSmsDAO dsd = (DdSmsDAO) ctx.getBean("DdSmsDAO");
					List list = dsd.findToSend();
					if (list.size() != 0) {
						DdSms ds = (DdSms) list.get(0);
						SmsSend ss = new SmsSend();
						String res = ss.sendSms(ds.getPhone(), ds.getSendmsg().replaceFirst("10000", "1OOOO"));
						if(ds.getTypes()!=null){
							if(ds.getTypes().intValue()==1&&ds.getOrderstatus().intValue()==1){//新单提醒同时提醒客服
								ss.sendSms("15880003555", ds.getSendmsg());
								ss.sendSms("13859082524", ds.getSendmsg());
								ss.sendSms("18060474139", ds.getSendmsg());
							}
						}
						
						if (!res.equals("")) {
							ds.setMsgid(Integer.parseInt(res));
							ds.setStatus(1);
							ds.setMasstatus(1);
						} else {
							DdSms dss = new DdSms();
							dss.setCreatedate(new Date());
							dss.setStatus(0);
							dss.setOrderid(ds.getOrderid());
							dss.setOrderstatus(ds.getOrderstatus());
							dss.setPhone(ds.getPhone());
							dss.setSendmsg(ds.getSendmsg());
							dss.setTypes(ds.getTypes());
							dsd.saveOrUpdate(dss);
							ds.setStatus(4);
						}
						dsd.saveOrUpdate(ds);
					}
				}
				isRunning = false;
			} else {
				logger.info("[SmsSendTask]-The last task is not over");
			}
			

		} catch (Exception e) {
			e.printStackTrace();
			this.logger.error(e.toString());
			isRunning = false;
		}

	}
}
